package com.netease.nim.uikit.business.session.activity;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.netease.nim.uikit.api.model.session.SessionEventListener;
import com.netease.nim.uikit.business.team.model.UserInfo;
import com.netease.nim.uikit.common.ToastHelper;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.netease.nim.uikit.R;
import com.netease.nim.uikit.api.NimUIKit;
import com.netease.nim.uikit.api.model.contact.ContactChangedObserver;
import com.netease.nim.uikit.api.model.main.OnlineStateChangeObserver;
import com.netease.nim.uikit.api.model.session.SessionCustomization;
import com.netease.nim.uikit.api.model.user.UserInfoObserver;
import com.netease.nim.uikit.business.session.constant.Extras;
import com.netease.nim.uikit.business.session.fragment.MessageFragment;
import com.netease.nim.uikit.business.uinfo.UserInfoHelper;
import com.netease.nim.uikit.impl.NimUIKitImpl;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.Observer;
import com.netease.nimlib.sdk.msg.MessageBuilder;
import com.netease.nimlib.sdk.msg.MsgService;
import com.netease.nimlib.sdk.msg.MsgServiceObserve;
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum;
import com.netease.nimlib.sdk.msg.model.CustomNotification;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.tandong.bottomview.view.BottomView;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;


/**
 * 点对点聊天界面
 * <p/>
 * Created by huangjun on 2015/2/1.
 */
public class P2PMessageActivity extends BaseMessageActivity {
    private BottomView bottomView;
    private void showPopWindow(){
        bottomView=new BottomView(P2PMessageActivity.this,R.style.BottomViewTheme_Defalut,R.layout.item_select);
        bottomView.setAnimation(R.style.myStyle);
        bottomView.dismissBottomView();
        bottomView.showBottomView(false);
        TextView txt_1= bottomView.getView().findViewById(R.id.txt_1);
        TextView txt_2= bottomView.getView().findViewById(R.id.txt_2);
        TextView txt_exit= bottomView.getView().findViewById(R.id.txt_exit);
        txt_1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                bottomView.dismissBottomView();
//                fragment.setType("2");
                SessionTypeEnum sessionType = SessionTypeEnum.P2P;
                IMMessage textMessage = MessageBuilder.createTextMessage(sessionId, sessionType, "咨询已结束，请评价");
                Map<String, Object> data = new HashMap<>();
                data.put("messageType", "0");
                data.put("messagePosition", "0");
                textMessage.setRemoteExtension(data);
                fragment.sendMessage(textMessage);

            }
        });
        txt_2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setMessage(UserInfoHelper.getUserTitleName(sessionId, SessionTypeEnum.P2P),sessionId);
                bottomView.dismissBottomView();

            }
        });
        txt_exit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                bottomView.dismissBottomView();

            }
        });

    }
    public void setMessage(String nickName,String toUserId){

    }
    public void setCommit(long uid,String counsoler,String toUserId){

    }

    @Override
    protected int setStatusBarColor() {
        return getResources().getColor(R.color.chat_top);
    }

    private boolean isResume = false;
    public UserInfo getUserInfoFromDb(Context context) {
        if (context == null) return null;
        UserInfo user = new UserInfo();
        Cursor cursor = null;
        try {
            cursor = context.getContentResolver().query(ProviderUser.User.CONTENT_URI, null
                    , null, null, null);
            if (cursor != null && cursor.getCount() > 0 && cursor.moveToFirst()) {
                String data = cursor.getString(cursor.getColumnIndex(ProviderUser.User.DATA));
                if (!TextUtils.isEmpty(data)) {
                    user = new Gson().fromJson(data, UserInfo.class);
                    return user;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null) cursor.close();
        }
        return user;
    }

    public static void start(Context context, String contactId, SessionCustomization customization, IMMessage anchor) {
        Intent intent = new Intent();
        intent.putExtra(Extras.EXTRA_ACCOUNT, contactId);
        intent.putExtra(Extras.EXTRA_CUSTOMIZATION, customization);
        if (anchor != null) {
            intent.putExtra(Extras.EXTRA_ANCHOR, anchor);
        }
        intent.setClass(context, P2PMessageActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        context.startActivity(intent);
    }
    private TextView nickName;
    private ImageView right_top;
    private LinearLayout back_lay,config;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 单聊特例话数据，包括个人信息，
        nickName=findViewById(R.id.nickName);
        right_top=findViewById(R.id.right_top);
        requestBuddyInfo();
        displayOnlineState();
        registerObservers(true);
        findViewById(R.id.back_lay).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        findViewById(R.id.config).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setMessage(right_top,sessionId);
            }
        });
        NimUIKit.setSessionListener(new SessionEventListener() {
            @Override
            public void onAvatarClicked(Context context, IMMessage message) {
                try {
                        if(userInfo!=null&&userInfo.getType()!=null&&userInfo.getType().equals("2")){
                            if(userInfo!=null&&userInfo.getType()!=null&&!message.getFromAccount().equals(String.valueOf(userInfo.getYunxinAccount()))){
                                Intent to=new Intent();
                                to.setClass(P2PMessageActivity.this,Class.forName("com.tj.jinzao.activity.PersonInfoOtherActivity"));
                                to.putExtra("type",1);
                                to.putExtra("id",message.getFromAccount());
                                startActivity(to);
                            }else {
//                                PersonZXSActivity
                                Intent to=new Intent();
                                to.setClass(P2PMessageActivity.this,Class.forName("com.tj.jinzao.activity.PersonZXSEditActivity"));
                                to.putExtra("id",message.getFromAccount());
                                startActivity(to);

                            }


                        }else {
                            if(userInfo!=null&&userInfo.getType()!=null&&!message.getFromAccount().equals(String.valueOf(userInfo.getYunxinAccount()))){
                                Intent to=new Intent();
                                to.setClass(P2PMessageActivity.this,Class.forName("com.tj.jinzao.activity.PersonZXSActivity"));
                                to.putExtra("id",message.getFromAccount());
                                startActivity(to);

                            }else {
                                Intent to=new Intent();
                                to.setClass(P2PMessageActivity.this,Class.forName("com.tj.jinzao.activity.PersonInfoActivity"));
                                to.putExtra("id",message.getFromAccount());
                                startActivity(to);

                            }



                        }





                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onAvatarLongClicked(Context context, IMMessage message) {

            }

            @Override
            public void onAckMsgClicked(Context context, IMMessage message) {

            }
        });
        fragment.setOnCommentLinstener(new MessageFragment.onCommentLinstener() {
            @Override
            public void onComment(String star) {
                setCommit(userInfo.getId(),userInfo.getCounselor(),star);
            }
        });
    }

    public void setMessage(ImageView right_top,String id){
        if(userInfo==null){
            return;
        }
        if(userInfo!=null&&userInfo.getType()!=null&&userInfo.getType().equals("2")){
            showPopWindow();
        }else {
            finish();
            Intent to=new Intent();
            to.setClass(P2PMessageActivity.this,MessageActivity.class);
            startActivity(to);
        }

    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        registerObservers(false);
    }

    @Override
    protected void onResume() {
        super.onResume();
        isResume = true;
        fragment.setType(userInfo.getType(),String.valueOf(userInfo.getId()));
    }

    @Override
    protected void onStop() {
        super.onStop();
        isResume = false;
    }

    UserInfo userInfo;
    private void requestBuddyInfo() {
        nickName.setText(UserInfoHelper.getUserTitleName(sessionId, SessionTypeEnum.P2P));
        userInfo= getUserInfoFromDb(P2PMessageActivity.this);
        Log.w("数据用户信息===",""+userInfo.toString());

        if(userInfo!=null&&userInfo.getType()!=null&&userInfo.getType().equals("2")){
            right_top.setImageResource(R.drawable.more);
        }else {
            right_top.setImageResource(R.drawable.chat);
        }
//        setTitle(UserInfoHelper.getUserTitleName(sessionId, SessionTypeEnum.P2P));
    }

    private void displayOnlineState() {
        if (!NimUIKitImpl.enableOnlineState()) {
            return;
        }
        String detailContent = NimUIKitImpl.getOnlineStateContentProvider().getDetailDisplay(sessionId);
        setSubTitle(detailContent);
    }


    /**
     * 命令消息接收观察者
     */
    private Observer<CustomNotification> commandObserver = new Observer<CustomNotification>() {
        @Override
        public void onEvent(CustomNotification message) {
            if (!sessionId.equals(message.getSessionId()) || message.getSessionType() != SessionTypeEnum.P2P) {
                return;
            }
            showCommandMessage(message);
        }
    };


    /**
     * 用户信息变更观察者
     */
    private UserInfoObserver userInfoObserver = new UserInfoObserver() {
        @Override
        public void onUserInfoChanged(List<String> accounts) {
            if (!accounts.contains(sessionId)) {
                return;
            }
            requestBuddyInfo();
        }
    };

    /**
     * 好友资料变更（eg:关系）
     */
    private ContactChangedObserver friendDataChangedObserver = new ContactChangedObserver() {
        @Override
        public void onAddedOrUpdatedFriends(List<String> accounts) {
            setTitle(UserInfoHelper.getUserTitleName(sessionId, SessionTypeEnum.P2P));
        }

        @Override
        public void onDeletedFriends(List<String> accounts) {
            setTitle(UserInfoHelper.getUserTitleName(sessionId, SessionTypeEnum.P2P));
        }

        @Override
        public void onAddUserToBlackList(List<String> account) {
            setTitle(UserInfoHelper.getUserTitleName(sessionId, SessionTypeEnum.P2P));
        }

        @Override
        public void onRemoveUserFromBlackList(List<String> account) {
            setTitle(UserInfoHelper.getUserTitleName(sessionId, SessionTypeEnum.P2P));
        }
    };

    /**
     * 好友在线状态观察者
     */
    private OnlineStateChangeObserver onlineStateChangeObserver = new OnlineStateChangeObserver() {
        @Override
        public void onlineStateChange(Set<String> accounts) {
            if (!accounts.contains(sessionId)) {
                return;
            }
            // 按照交互来展示
            displayOnlineState();
        }
    };

    private void registerObservers(boolean register) {
        NIMClient.getService(MsgServiceObserve.class).observeCustomNotification(commandObserver, register);
        NimUIKit.getUserInfoObservable().registerObserver(userInfoObserver, register);
        NimUIKit.getContactChangedObservable().registerObserver(friendDataChangedObserver, register);
        if (NimUIKit.enableOnlineState()) {
            NimUIKit.getOnlineStateChangeObservable().registerOnlineStateChangeListeners(onlineStateChangeObserver, register);
        }
    }


    protected void showCommandMessage(CustomNotification message) {
        if (!isResume) {
            return;
        }
        String content = message.getContent();
        try {
            JSONObject json = JSON.parseObject(content);
            int id = json.getIntValue("id");
            if (id == 1) {
                // 正在输入
                ToastHelper.showToastLong(P2PMessageActivity.this, "对方正在输入...");
            } else {
                ToastHelper.showToast(P2PMessageActivity.this, "command: " + content);
            }
        } catch (Exception ignored) {

        }
    }
    MessageFragment fragment;
    @Override
    protected MessageFragment fragment() {
        Bundle arguments = getIntent().getExtras();
        arguments.putSerializable(Extras.EXTRA_TYPE, SessionTypeEnum.P2P);
        fragment = new MessageFragment();
        fragment.setArguments(arguments);
        fragment.setContainerId(R.id.message_fragment_container);
        return fragment;
    }

    @Override
    protected int getContentViewId() {
        return R.layout.nim_message_activity;
    }

    @Override
    protected void initToolBar() {
//        ToolBarOptions options = new NimToolBarOptions();
//        setToolBar(R.id.toolbar, options);
    }

    @Override
    protected boolean enableSensor() {
        return true;
    }
}
